const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const pool = require('../db'); // 引入数据库连接池
const router = express.Router();

// 登录路由
router.post('/indexLogin', async (req, res) => {
    const { username, password } = req.body;

    try {
        // 查找用户
        const user = await User.findOne(username);
        if (!user) {
            return res.status(400).json({ msg: 'Invalid credentials' });
        }

        // 验证密码
        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            return res.status(400).json({ msg: 'Invalid credentials' });
        }

        // 生成JWT
        const payload = {
            user: {
                id: user.id
            }
        };

        jwt.sign(
            payload,
            'secretkey',
            { expiresIn: 3600 },
            (err, token) => {
                if (err) throw err;
                res.json({ token });
            }
        );
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server error');
    }
});

// 注册路由
router.post('/indexSign', async (req, res) => {
    const { username, password, email } = req.body;

    try {
        // 检查用户是否已存在
        const user = await User.findOne(username);
        if (user) {
            return res.status(400).json({ msg: 'User already exists' });
        }

        // 加密密码
        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(password, salt);

        // 创建新用户
        const userId = await User.create(username, hashedPassword, email);

        // 生成JWT
        const payload = {
            user: {
                id: userId
            }
        };

        jwt.sign(
            payload,
            'secretkey',
            { expiresIn: 3600 },
            (err, token) => {
                if (err) throw err;
                res.json({ token });
            }
        );
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server error');
    }
});

module.exports = router;